##Developed by Florin Nicusor Coada for 216CR
##Based on the tutorial offered by Christopher Peters
import sqlite3 as sqlite
import SimpleXMLRPCServer 

##connect to the database and create a simple users table
con = sqlite.connect(":memory:")
con.execute("create table users(name varchar primary key, pass varchar, ban integer, admin integer)")
cur=con.cursor()
cur.execute("insert into users values ('Florin','cocouta',0,1)")
cur.execute("insert into users values('Dudu','cainerosu',0,0)")
cur.execute("insert into users values('Coco','spammer',0,0)")
cur.execute("insert into users values('Fraguta','cocotat',0,0)")
cur.execute("insert into users values('q','q',1,0)")

class User:
    def __init__(self):
        self.users={}
    ##check to see if login details are correct 
    def checkUser(self,name,passw):
        cur.execute("select * from users where name like '{0}'".format(name))
        for item in cur:
            if(item[0]==name and item[1]==passw):
                if(item[2]==1):
                    return 2
                return 1
        return 0

    ##add another user to the database
    def addUser(self,name,passw):
        cur.execute("select name from users where name like '{0}'".format(name))
        for item in cur:
            if(str(item[0]).upper()==name.upper()):
                return 0
        cur.execute("insert into users values ('{0}','{1}',0,0)".format(name,passw))
        return 1

    ##check to see if user has admin privileges
    def userType(self,name):
        cur.execute("select admin,name from users where name like '{0}'".format(name))
        for item in cur:
            if(item[0]==1):
                return 1
            else :
                return 0
            
    ##change the name of an existing user
    def newName(self,name,newname):
        cur.execute("select name from users where name like '{0}'".format(newname))
        for item in cur:
            if(str(item[0]).upper()==newname.upper()):
                return 0        
        cur.execute("update users set name='{0}' where name like '{1}'".format(newname,name))
        return 1

    ##change the password of an existing user
    def newPassword(self,oldpass,newpass,name):
        cur.execute("select pass from users where name like '{0}'".format(name))
        for item in cur:
            if(item[0]==oldpass):
                cur.execute("update users set pass='{0}' where name like '{1}'".format(newpass,name))
                return 1
        return 0

    ##ban a user
    def banUser(self,name):
        cur.execute("update users set ban=1 where name like '{0}'".format(name))
        return 1
        
user_obj=User()
server=SimpleXMLRPCServer.SimpleXMLRPCServer(("192.168.1.2", 8888))
server.register_instance(user_obj)        
#Go into the main listener loop
server.serve_forever()
